/*
 * @Date: 2022-02-27 22:39:05
 * @LastEditors: Wangjun
 * @LastEditTime: 2023-05-30 23:31:24
 * @FilePath: \golib\winextend\c\winextend.c
 * @Description:
 */

#include <windows.h>
#include <stdio.h>

#ifdef __cplusplus
extern "C"
{
#endif

    HWND WindowFromPointXY(int x, int y);
    HWND FindWindowFromPidTitle(int pid, const WCHAR *title);

    BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam);

#ifdef __cplusplus
}
#endif

typedef struct
{
    DWORD ProcessID;
    HWND wnd;
    const WCHAR *Title;
} WndData;

// gcc --shared winextend.c -o win64.dll
// gcc -m32 --shared winextend.c -o win32.dll
HWND WindowFromPointXY(int x, int y)
{
    POINT point;
    point.x = x;
    point.y = y;
    return WindowFromPoint(point);
}

HWND FindWindowFromPidTitle(int pid, const WCHAR *title)
{
    WndData wd;
    wd.wnd = NULL;
    wd.ProcessID = pid;
    wd.Title = title; //
    EnumWindows(EnumWindowsProc, (LPARAM)&wd);
    return wd.wnd;
}

BOOL CALLBACK EnumChildProc(_In_ HWND hwnd, _In_ LPARAM lParam)
{
    WCHAR szTitle[MAX_PATH] = {0};
    int nMaxCount = MAX_PATH;
    GetWindowTextW(hwnd, szTitle, nMaxCount);
    WndData *wd = (WndData *)lParam;
    if (wcscmp(szTitle, wd->Title) == 0)
    {
        // printf("==================%ls, %ls , %p\n", szTitle, wd->Title, hwnd);
        wd->wnd = hwnd;
        return FALSE;
    }
    return TRUE;
}

BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam)
{
    WCHAR szTitle[MAX_PATH] = {0};
    WCHAR szClass[MAX_PATH] = {0};
    int nMaxCount = MAX_PATH;

    // GetWindowTextW(hwnd, szTitle, nMaxCount);
    DWORD lpdwProcessId;
    GetWindowThreadProcessId(hwnd, &lpdwProcessId);
    WndData *wd = (WndData *)lParam;
    if (wd->ProcessID == lpdwProcessId)
    {
        if (wcscmp(szTitle, wd->Title) == 0)
        {
            wd->wnd = hwnd;
            return FALSE;
        }
        EnumChildWindows(hwnd, EnumChildProc, lParam);
    }
    return TRUE;
}

int main()
{
    HWND hwnd = FindWindowFromPidTitle(22220, L"今日不再提示");
    printf(" %p\n", hwnd);

    return 0;
}